import dynamic from 'next/dynamic'
import Layout from '@c/layout'
import Responsive from '@c/responsive'
import message from '@c/message'
import styles from './index.module.scss'
import cm from 'classnames'
import { useEffect, useState, useMemo } from 'react'
import { getShuffleHots } from '@/utils/utils'
import { useShowLogin } from '@/utils/hooks'
import Link from 'next/link'
import { getPlayUrl, orderFocus, cancelOrderFocus, getRaceDetail } from '@/api/sports'
import Copy from 'clipboard'
import { pcStore } from '@/store'
import { useRecoilValue } from 'recoil'
import { useRouter } from 'next/router'

const PlayErrorPc = dynamic(() => import('@c/play-error-pc'))
const PlayErrorPhone = dynamic(() => import('@c/play-error-phone'))
const Deadline = dynamic(() => import('@c/sports/deadline'))
const PlaybackBox = dynamic(() => import('@c/sports/playback-box'))
const VideoSportsHls = dynamic(() => import('@c/video/video-sports-hls'))
const VideoSportsMp4 = dynamic(() => import('@c/video/video-sports-mp4'))
const VideoSportsVip = dynamic(() => import('@c/video/video-sports-hls-vip'))
const DownloadPhone = dynamic(() => import('@c/download/download-phone'))
const DownloadTv = dynamic(() => import('@c/download/download-tv'))
const ArrowSvg = dynamic(() => import('@c/svg/arrow'))
const VideoSportsFlv = dynamic(() => import('@c/video/video-flv'))

const Index = props => {
  const { id, purl, raceDetail, shuffleHots } = props
  const [playUrl, setPlayUrl] = useState(purl)
  const [playError, setError] = useState(false)
  const isPhone = !useRecoilValue(pcStore)
  const router = useRouter()
  const setShowLogin = useShowLogin()
  const [isOrder, setOrdered] = useState(false)
  const [status, setStatus] = useState(raceDetail.status)
  const [noStart, setNoStart] = useState(status == 0 || status == 3) //未开始
  const [playing, setPlaying] = useState(status == 1) //直播中
  useEffect(() => {
    //获取比赛详情
    getRaceDetail(id, localStorage.getItem('token')).then(res => {
      if (res.code === 0) {
        setOrdered(res?.data?.isFocus)
      }
    })
    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [])

  const handlePlayError = () => {
    setError(true)
  }

  //倒数计时结束，开始直播
  const beginLive = async () => {
    const res = await getPlayUrl({ id })
    setPlayUrl(generateUrl(res?.data?.purl || ''))
    setPlaying(true)
    setNoStart(false)
    setStatus(1)
  }

  // 是否是mp4回放地址
  const isPlaybackUrl = useMemo(() => {
    return {
      isMp4: playUrl && !playUrl.includes('.m3u8'),
      isM3u8: playUrl && playUrl.includes('.m3u8')
    }
  }, [playUrl])

  //title node
  const titleNode = useMemo(() => {
    const { title } = raceDetail
    const teamGroup = raceDetail?.confrontTeams || []
    if (teamGroup.length < 2) {
      return <div className={styles.competition}>{title}</div>
    }
    return (
      <div className={styles.userBox}>
        <div className={styles.userItem}>
          <img loading="lazy" src={teamGroup[0].image} alt={teamGroup[0].name} className={styles.teamImg} />
          <span className={cm(styles.teamName, 'textEllipsis')}>{teamGroup[0].name}</span>
          <span className={styles.teamScore}>{status == 0 || status == 3 ? '--' : teamGroup[0].score}</span>
        </div>
        <img src="/images/vs.webp" alt="vs" className={styles.vs} />
        <div className={styles.userItem}>
          <img loading="lazy" src={teamGroup[1].image} alt={teamGroup[1].name} className={styles.teamImg} />
          <span className={cm(styles.teamName, 'textEllipsis')}>{teamGroup[1].name}</span>
          <span className={styles.teamScore}>{status == 0 || status == 3 ? '--' : teamGroup[1].score}</span>
        </div>
      </div>
    )
  }, [isPhone, raceDetail, id])

  // 预约与取消预约
  const orderOrCancel = () => {
    if (isOrder) {
      cancelOrder()
    } else {
      orderRace()
    }
  }
  //预约
  const orderRace = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      setShowLogin(true)
      return
    }
    const res = await orderFocus({ id }, token)
    if (res?.code === 0) {
      setOrdered(true)
      message({ content: '加入焦点赛成功' })
    }
  }
  // 取消预约
  const cancelOrder = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      setShowLogin(true)
      return
    }
    const res = await cancelOrderFocus({ id }, token)
    if (res?.code === 0) {
      setOrdered(false)
      message({ content: '取消加入焦点赛' })
    }
  }

  // 分享点播
  const urlMemo = useMemo(() => {
    const str = `这场<${raceDetail?.confrontTeams?.length ? raceDetail.title : raceDetail.competition
      }>太精彩了，快来星视界一起看！免费高清观看地址：https://www.histar.tv//sports/live/${id}`
    return str
  }, [id])
  useEffect(() => {
    const copyUrl = new Copy('.share-sports-btn')
    copyUrl.on('success', () => {
      message({ content: '链接复制成功，分享给好友可领积分兑免费会员~' })
    })
    const copyUrl1 = new Copy('.share-sports-btn1')
    copyUrl1.on('success', () => {
      message({ content: '链接复制成功，分享给好友可领积分兑免费会员~' })
    })
  }, [])

  const playName = useMemo(() => {
    const { title, confrontTeams } = raceDetail
    const teamGroup = raceDetail?.confrontTeams || []
    if (!confrontTeams?.length) {
      return title
    }
    return `${title}_${teamGroup[0].name}${teamGroup[0].score}:${teamGroup[1].score}${teamGroup[1].name}`
  }, [id])

  return (
    <>
      <Responsive className={styles.playContainer}>
        <div className={cm(styles.playBox, styles.playBoxPhone)}>
          <div className={styles.playArea}>
            <div className={styles.play}>
              {playError ? isPhone ? <PlayErrorPhone /> : <PlayErrorPc /> : null}
              {noStart ? <Deadline deadline={raceDetail.startTime} onEnd={beginLive} /> : null}
              {playing ? (
                playUrl.includes('miguvideo.com')
                  ?
                  (playUrl.includes('flv') ? <VideoSportsFlv
                    from="SPORT"
                    name={playName}
                    lineArr={[playUrl]}
                    onError={handlePlayError}
                    isCollected={isOrder}
                  /> : <VideoSportsVip
                    name={playName}
                    lineArr={[playUrl]}
                    onError={handlePlayError}
                    isCollected={isOrder}
                    useCustomLoader={true}
                  />
                  )
                  :
                  <VideoSportsVip
                    name={playName}
                    lineArr={[playUrl]}
                    onError={handlePlayError}
                    isCollected={isOrder}
                  />
              ) : null}
              {status == 2 ? (
                isPlaybackUrl.isMp4 ? (
                  <VideoSportsMp4
                    from="SPORT"
                    lineArr={[playUrl]}
                    onError={handlePlayError}
                    isCollected={isOrder}
                    name={playName}
                  />
                ) : isPlaybackUrl.isM3u8 ? (
                  <VideoSportsHls
                    hideProgress={false}
                    hideSpeed={false}
                    from="SPORT"
                    lineArr={[playUrl]}
                    onError={handlePlayError}
                    isCollected={isOrder}
                    useCustomLoader={true}
                    name={playName}
                  />
                ) : (
                  <PlaybackBox />
                )
              ) : null}
            </div>
            <div className={cm(styles.playMenu, 'hideWhenPhone')}>
              <div className={styles.menuLeft}>
                <div className={cm(styles.btn, isOrder ? styles.btnCollected : '')} onClick={orderOrCancel}>
                  <img src={'/images/' + (isOrder ? 'collect_active.png' : 'collect_page.png')} alt="收藏" />
                  {isOrder ? '已' : ''}加入焦点赛
                </div>
                <div className={cm(styles.btn, styles.btnShare, 'share-sports-btn')} data-clipboard-text={urlMemo}>
                  <img src="/images/share.png" alt="分享" />
                  分享
                  <img src="/images/corn.webp" alt="corn" className={styles.corn} />
                </div>
              </div>
              <div className={styles.menuRight}>
                <div className={cm(styles.btn, styles.btnMore)} onClick={() => router.push('/download?to=phone')}>
                  <img src="/images/collect_page.png" alt="收藏" />
                  手机随时看
                  <DownloadPhone className={styles.btnHover} />
                </div>
                <div className={cm(styles.btn, styles.btnMore)} onClick={() => router.push('/download?to=tv')}>
                  <img src="/images/tv-download.png" alt="收藏" />
                  TV大屏观看
                  <DownloadTv className={styles.btnHover} />
                </div>
              </div>
            </div>
          </div>
          <div className={cm(styles.sectionBox, 'hideWhenPhone')}>
            <h1 className={cm(styles.titleName, 'textEllipsis')}>
              {raceDetail?.confrontTeams?.length ? raceDetail.title : raceDetail.competition}
            </h1>
            <div className={styles.teamDate}>
              <div>
                <span>{raceDetail.keyWord.slice(0, 6)}</span>
                <span className={styles.titleSpace}>{raceDetail.keyWord.slice(-5)}</span>
              </div>
              <span
                className={cm(styles.statusBtn, {
                  [styles.statusNoStart]: status === 0,
                  [styles.statusLiving]: status === 1,
                  [styles.statusEnd]: status !== 0 && status !== 1
                })}
              >
                {status == 0 ? ' 未开始' : status == 1 ? '直播中' : '已结束'}
              </span>
            </div>
            {titleNode}
          </div>
        </div>
      </Responsive>
      <Layout>
        <div className={cm(styles.hotRace, 'hideWhenPhone')}>
          <div className={styles.hotLeft}>
            <img loading="lazy" src="/images/sports/hotRace.png" alt="热门" />
          </div>
          <div className={styles.hotRight}>
            {shuffleHots?.map((item, index) => {
              return (
                <Link href={`/sports/${item.url}`} className={styles.hotItem} key={index}>
                  <img loading="lazy" src={item.icon} alt={item.name} />
                  <span>{item.name}</span>
                </Link>
              )
            })}
          </div>
        </div>
        <div className="hideWhenPc">
          <div className={styles.titlePhone}>
            {playName.split('_').length > 1 ? (
              <>
                <span>{playName.split('_')[0]}</span>
                <ArrowSvg className={styles.arrow} width={12} />
                <span>{playName.split('_')[1]}</span>
              </>
            ) : (
              <span>{playName}</span>
            )}
          </div>
          <div className={styles.teamDatePhone}>
            <div>
              <span>{raceDetail.keyWord.slice(0, 6)}</span>
              <span className={styles.titleSpace}>{raceDetail.keyWord.slice(-5)}</span>
            </div>
            <span
              className={cm(styles.statusBtn, {
                [styles.statusNoStart]: status === 0,
                [styles.statusLiving]: status === 1,
                [styles.statusEnd]: status !== 0 && status !== 1
              })}
            >
              {status == 0 ? ' 未开始' : status == 1 ? '直播中' : '已结束'}
            </span>
          </div>
          <div className={styles.playMenuPhone}>
            <div className={cm(styles.btn, isOrder ? styles.btnCollected : '')} onClick={orderOrCancel}>
              <img src={'/images/' + (isOrder ? 'collect_active.png' : 'collect_page.png')} alt="收藏" />
            </div>
            <div className={cm(styles.btn, styles.btnShare, 'share-sports-btn1')} data-clipboard-text={urlMemo}>
              <img src="/images/share.png" alt="分享" />
              <img src="/images/corn.webp" alt="corn" className={styles.corn} />
            </div>
          </div>
        </div>
        <div className={cm(styles.hotRacePhone, 'hideWhenPc')}>
          <div className={styles.hotTitle}>热门赛事</div>
          <div className={cm(styles.hotMain, 'scrollBeautify')}>
            {shuffleHots?.map((item, index) => {
              return (
                <Link href={`/sports/${item.url}`} className={styles.hotItem} key={index}>
                  <img loading="lazy" src={item.icon} alt={item.name} />
                  <span className="textEllipsis">{item.name}</span>
                </Link>
              )
            })}
          </div>
        </div>
      </Layout>
    </>
  )
}

export default Index

const generateUrl = liveUrl => {
  if (!liveUrl) {
    return ''
  }
  const newUrl = liveUrl.replace('http://', 'https://')
  return newUrl
}

export async function getServerSideProps({ params }) {
  const { id } = params
  const resArr = (await Promise.allSettled([getPlayUrl({ id }, {}), getRaceDetail(id, '')]))?.map(item => {
    if (item.value.code === 0) {
      return item.value?.data || {}
    }
    return {}
  })
  try {
    if (!resArr[1].matchID) {
      return { notFound: true }
    }
  } catch (error) {
    return { notFound: true }
  }
  // 获取随机热门赛事
  const shuffleHots = getShuffleHots()
  const raceDetail = resArr[1]
  let time = null
  try {
    time = new Date(raceDetail.startTime).getFullYear() + '年'
  } catch (error) { }
  return {
    props: {
      shuffleHots,
      id,
      purl: resArr[0]?.purl || '',
      raceDetail,
      layoutProps: {
        noSomeMetaInfo: false,
        title: `${raceDetail?.title} - 星视界`,
        desc: `${time}${raceDetail?.keyWord}${raceDetail?.title}比赛全程直播及视频回看。`,
        url: '/sports'
      }
    }
  }
}
